import {
  ArgumentMetadata,
  Inject,
  Injectable,
  PipeTransform,
} from '@nestjs/common'
import { REQUEST } from '@nestjs/core'
import { ClsService } from 'nestjs-cls'

import { OperatorDto } from '../dto/operator.dto'

@Injectable()
export class UpdaterPipe implements PipeTransform {
  constructor(
    @Inject(REQUEST) private readonly request: any,
    private readonly cls: ClsService,
  ) {}

  transform(value: OperatorDto, metadata: ArgumentMetadata) {
    const user = this.request.user as IAuthUser

    value.updateBy = user.uid

    // 如果是更新操作且有id字段，设置operateId供唯一性验证使用
    if ((value as any).id && Number.isInteger((value as any).id)) {
      console.log('UpdaterPipe: Setting operateId to', (value as any).id)
      this.cls.set('operateId', (value as any).id)
    }

    return value
  }
}
